<template>
  <div class="app-container">
    <list-admin
      ref="admin"
      :key="componentRefresh"
      v-model="listData"
      :entity-conf="entity"
      :list-display="fields"
      :disabled-actions="disabled"
      :query="query"
      :config="config"
      :actions="actions"
      :data-processor="dataProcessor"
    >
      <template v-slot:titleText>
        <span>人员管理</span>
      </template>
      <template v-slot:extraTopButton>
        <span style="margin-right: .5em">
          <el-input v-model="search.name" placeholder="名称" style="width: 150px;" size="medium" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </span>
        <span style="margin-right: .5em">
          <el-input v-model="search.phone" placeholder="电话" style="width: 150px;" size="medium" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search" />
          </el-input>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.squad" style="width: 150px;" size="medium" clearable placeholder="小队">
            <el-option v-for="item in squads" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.team" style="width: 150px;" size="medium" clearable placeholder="团队">
            <el-option v-for="item in teams" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="search.status" style="width: 150px;" size="medium" clearable placeholder="状态">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
      </template>
    </list-admin>

  </div>
</template>

<script>
import ListAdmin from '@/components/EasyAdmin/ListAdmin'
import admin from '@/config'

export default {
  components: { ListAdmin },
  data() {
    return {
      showRole: false,
      entity: '',
      alias: '',
      config: {},
      fields: [],
      query: {},
      disabled: [],
      entityParam: this.$route.params.entityParam,
      listData: [],
      componentRefresh: 0,
      actions: [],
      filter: {},
      squads: [],
      teams: [],
      roles: [],
      options: [
        { id: 1, name: '在职' },
        { id: 2, name: '离职' }
      ],
      selections: [],
      chooseRole: '',
      search: {
        id: null,
        name: null,
        phone: null,
        squad: null,
        team: null,
        role: null,
        status: null
      },
      dialog: {
        visible: false,
        loading: false,
        bond: { checked: false, value: 0 },
        unBond: { checked: false },
        fee: { checked: false, value: 0 }
      },
      extraData: {
        isPrincess: false, // 房间公主
        isBooker: false, // 小程序订房
        isCashier: false, // 查看所有订单
        canCashier: false, // 查看自己下单房间的订单
        noStatistics: false, // 不能查看统计数据
        changeRoule: false, // 作为队长/经纪时候可修改角色
        edit: false, // 作为管理员时候有修改权限
        canPenaltie: false, // 可执行扣罚
        noCancelOrder: false, // 不可取消订单
        noChangeSquad: false, // 可修改员工小队
        noChangeRole: false, // 可修改员工角色
        attendanceOrder: false, // 打卡才能下单
        canExecuteSettle: false, // 操作分账
        // depositCommission: 0
      },
      showRoles: false
    }
  },
  created() {
    // Load entities data
    this.alias = 'StoreStaff'
    this.store = localStorage.getItem('storeId')

    if (!Object.keys(admin.entities).includes(this.alias)) {
      console.log('NO!')
    } else {
      this.config = admin.entities[this.alias]
      this.entity = Object.keys(this.config).includes('entity') ? this.config.entity : this.alias
      this.fields = this.config.list.list_display
      this.disabled = this.config.list.disabled_actions
      this.query = this.config.list.query
      this.actions = this.config.list.actions

      this.getSquads()
      this.getTeams()
      this.getRoles()
    }
  },
  methods: {
    clearDialog() {
      this.dialog.bond.checked = false
      this.dialog.bond.value = 0
      this.dialog.unBond.checked = false
      this.dialog.fee.checked = false
      this.dialog.fee.value = 0
    },
    submitRole() {
      const selections = this.selections
      console.log(selections)
      if (selections.length === 0) {
        this.$message.error('请先勾选修改项')
        return
      }
      const data = []
      for (var i of selections) {
        data.push({
          id: i.id,
          extraData: this.extraData
        })
      }
      console.log('data', data)
      this.axios.post(`/store/${this.store}/staffs/batch-update`, data, { params: { '@mode': 'mixed', '@basis': 'id' }}).then((res) => {
        this.$message.success('修改成功！')
        this.showRole = false
      })
    },
    // 批量修改角色
    submitRoles() {
      const selections = this.selections
      console.log(selections)
      if (selections.length === 0) {
        this.$message.error('请先勾选修改项')
        return
      }
      const data = []
      console.log(this.chooseRole)
      if (this.chooseRole === '') {
        this.$message.error('请选择角色')
        return
      }
      for (var i of selections) {
        data.push({
          id: i.id,
          role: this.chooseRole
        })
      }
      console.log('data', data)
      this.axios.post(`/store/${this.store}/staffs/batch-update`, data, { params: { '@mode': 'mixed', '@basis': 'id' }}).then((res) => {
        this.$message.success('修改成功！')
        this.showRoles = false
        this.chooseRole = ''
      })
    },
    submit() {
      const selections = this.selections
      console.log('selec', selections)
      if (selections.length === 0) {
        this.$message.error('请选择操作数据!')
        return
      }
      if (!this.dialog.bond.checked && !this.dialog.unBond.checked && !this.dialog.fee.checked) {
        this.$message.error('请选择执行设置!')
        return
      }
      if (this.dialog.bond.checked && this.dialog.unBond.checked) {
        this.$message.error('不能同时执行创建与退还保证金!')
        return
      }
      // 批量开户or修改保证金
      if (this.dialog.bond.checked) {
        if (isNaN(Number(this.dialog.bond.value))) {
          this.$message.error('请正确数字类型!')
          return
        }
        this.dialog.loading = true
        const data = []
        selections.map(v => {
          if (v.bond) {
            data.push({ id: v.bond.id, bond: Number(this.dialog.bond.value) })
          } else {
            data.push({ staff: v.id, bond: Number(this.dialog.bond.value) })
          }
        })
        this.axios.post(`/store/${this.store}/bonds/batch-update`, data, { params: { '@mode': 'mixed', '@basis': 'id' }})
          .then((res) => {
            this.$message.success('修改成功!')
            this.dialog.visible = false
            this.clearDialog()
            this.fetchData()
          })
          .finally(() => {
            this.dialog.loading = false
          })
        return
      }
      // 批量退还保证金
      if (this.dialog.unBond.checked) {
        this.dialog.loading = true
        const data = []
        const transactions = []
        const promise = []
        selections.map(v => {
          if (v.bond) {
            data.push({ id: v.bond.id, bond: 0 })
            if (v.bond.__metadata.balance > 0) {
              transactions.push({ type: 'bond-return', from: v.bond.__metadata.account.id, to: v.bond.__metadata.user.id, amount: v.bond.__metadata.balance, comment: '退还保证金' })
            }
          }
        })
        if (data.length > 0) {
          promise.push(
            this.axios.post(`/store/${this.store}/bonds/batch-update`, data, { params: { '@mode': 'mixed', '@basis': 'id' }})
          )
        }
        if (transactions.length > 0) {
          promise.push(
            this.axios.post(`/store/${this.store}/transactions/send`, transactions)
          )
        }
        Promise.all(promise).then((res) => {
          this.dialog.loading = false
          this.$message.success('修改成功!')
          this.dialog.visible = false
          this.clearDialog()
          this.fetchData()
        })
        return
      }

      // 批量添加入职费用
      if (this.dialog.fee.checked) {
        if (isNaN(Number(this.dialog.fee.value))) {
          this.$message.error('请正确数字类型!')
          return
        }
        if (this.dialog.fee.value <= 0) {
          this.$message.error('必须大于0!')
          return
        }
        this.dialog.loading = true
        const data = []
        selections.map(v => {
          data.push({ staff: v.id, payer: v.user.id, receiver: 105, amount: Number(this.dialog.fee.value), type: 'onboard-fee' })
        })
        this.axios.post(`/store/${this.store}/fees`, data)
          .then((res) => {
            this.$message.success('修改成功!')
            this.dialog.visible = false
            this.clearDialog()
            this.fetchData()
          })
          .finally(() => {
            this.dialog.loading = false
          })
        return
      }
    },
    settings(type) {
      const multipleSelection = this.$refs.admin.multipleSelection
      if (multipleSelection.length > 0) {
        this.selections = multipleSelection
        if (type === 0) {
          this.dialog.visible = true
        } else if (type === 1) {
          this.showRole = true
        } else if (type === 2) {
          this.showRoles = true
        }
      } else {
        this.$message.error('请选择操作数据!')
        this.selections = []
      }
    },
    getSquads() {
      this.axios.get(`/store/${this.store}/squads`, {
        params: {
          limit: 10000000
        }
      }).then(res => {
        this.squads = res.data
      })
    },
    getTeams() {
      this.axios.get(`/store/${this.store}/teams`, {
        params: {
          limit: 10000000
        }
      }).then(res => {
        this.teams = res.data
      })
    },
    getRoles() {
      this.axios.get(`/store/${this.store}/roles`, {
        params: {
          limit: 10000000
        }
      }).then(res => {
        this.roles = res.data
      })
    },
    fetchData() {
      this.$refs.admin.fetchData()
    },
    filterGenerate() {
      this.filter = {}
      if (this.search.id) {
        const expression = `entity.getId() == ${this.search.id}`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.name) {
        const expression = `entity.getName() matches '${this.search.name}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.phone) {
        const expression = `entity.getPhone() matches '${this.search.phone}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.squad) {
        const expression = `entity.getSquad().getId() == '${this.search.squad}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.team) {
        const expression = `entity.getSquad().getTeam().getId() == '${this.search.team}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.role) {
        const expression = `entity.getRole().getId() == '${this.search.role}'`
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
      if (this.search.status) {
        let expression = ''
        if (this.search.status > 1) {
          expression = `entity.getEnabled() == false`
        } else {
          expression = `entity.getEnabled() == true`
        }
        if (this.filter['@filter']) {
          this.filter['@filter'] += ` && ${expression}`
        } else {
          this.filter['@filter'] = `${expression}`
        }
      }
    },
    dataProcessor(context, dataProcessor = {}) {
      // Loading start
      context.list = []
      context.loading = true

      const promise = [
        // Fetch Structure
        context.em.structure().then(res => { context.structure = res }),

        // Fetch Data
        context.em.list(Object.assign(
          /**
               * Combine default constant query to dynamic pager and sort
               * Pager and sort object will change in the page
               */
          {},
          context.query ? context.query : {},
          this.filter,
          context.pager,
          context.sort
        )).then(res => {
          // Assign data
          context.list = res.data
          context.paginator = res.paginator
        })
      ]

      Promise.all(promise.map(p => p.catch(e => e)))
        .then(res => { context.loading = false })
    }
  }
}
</script>

<style lang="scss" scoped>
  .filterSpan {
    margin-right: .5em;
    margin-top: .5em
  }
</style>
